<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>添加采购需求</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="content-type" content="text/html;charset=utf-8">

<link rel="stylesheet" href="js/easyui/demo/demo.css" type="text/css"></link>
<link rel="stylesheet" href="js/easyui/themes/icon.css" type="text/css"></link>
<link rel="stylesheet" href="js/easyui/themes/default/easyui.css" type="text/css"></link>

<script type="text/javascript" src="js/easyui/jquery-1.6.min.js"></script>
<script type="text/javascript" src="js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="js/easyui/themes/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="script/common.js"></script>
<link href="css/style.css" rel="stylesheet" type="text/css">

<script type="text/javascript" charset="UTF-8">
	/**
	*打开产品窗口
	*/
	 function showProductList(){
	 	//打开窗口
 		$("#productList").window('open');
	 }
 
 	/**
	 * 根据制定页面跳转
	 */
	function bp_reload() {
		var offset = document.getElementById("bp_offset").value;
		var idx = (offset == null) ? 0 : parseInt(offset) - 1;
			
		var trgUrl = 'productgetAllProduct.action?offset=' + idx;
		$('#productList').window('refresh', trgUrl); 
	}

	/**
	 * 根据条件查询
	 */
	function bp_query() {
		var productCd=$("#bp_productCd").val();
		var brad = $("#bp_brad").combobox("getValue");
		var spno=$("#bp_spno").val();
		var jhdt = $("#bp_jhdt").datetimebox('getValue');
		var xjdt = $("#bp_xjdt").datetimebox('getValue');
		
		var trgUrl = 'productgetAllProduct.action?spno='+ spno+'&jhdt='+ jhdt+'&productCd='+ productCd
					+'&xjdt='+ xjdt+'&brad='+ brad;
					
		$('#productList').window('refresh', trgUrl); 
	}
	
	
	/**
	* 翻到给定偏移量的页面
	*/
	function bp_turnPage(offset){
	
		var productCd=$("#bp_productCd").val();
		var brad = $("#bp_brad").combobox("getValue");
		var spno=$("#bp_spno").val();
		var jhdt = $("#bp_jhdt").datetimebox('getValue');
		var xjdt = $("#bp_xjdt").datetimebox('getValue');
		
		var trgUrl = 'productgetAllProduct.action?spno='+ spno+'&jhdt='+ jhdt+'&productCd='+ productCd
					+'&xjdt='+ xjdt+'&brad='+ brad+ '&offset=' + offset;
					
		$('#productList').window('refresh', trgUrl); 
	}
 
 
 	/**
	 * 选择产品信息
	 * @param index
	 * @param value
	 */
	function chooseBProductP(index,value){ 
		var data_json = new Array();//定义一个json
		var productCd = value['productCode'].trim();	//获取选中的产品编码
		$('#productCode').textbox('setValue',productCd);//赋值
		$.ajax({
				type : 'POST',
				async: false,
				url : 'productgetProductSku',
				data : {
					'productCd' : productCd
				},
				dataType : 'json',
				success : function(data) {
				var i=1;//初始化序号1
					//循环json对象
					 for( var product in data.skuJsons) { 
					 	//DataGrid列配置对象，详见列属性说明中更多的细节。
					 	 var row_data = {
					 	 	code: i,
                    	 	skuCode : data.skuJsons[product].productDesc,
                    	 	cona : data.skuJsons[product].cona,
                    	 	szid : data.skuJsons[product].szid,
                    	 	purchaseNum:0,
                    	 	productCode:data.skuJsons[product].productCode,
                    	 	coloId:data.skuJsons[product].coloId,
                    	 	colo:data.skuJsons[product].colo,
                    	 	szco:data.skuJsons[product].szco
                     	 	};
                     	 	i++;
                     	 	
					     data_json.push(row_data);
				    }
				    
				    //添加尺寸checkbook
				    document.getElementById("sizeTr").innerHTML = "";  
				    for( var szid in data.szidJsons){ 
					 	 //获取颜色列id
                   		 var coloT = document.getElementById("sizeTr");
				    	 //插入td 
                   		 var ct = coloT.insertCell();
                   		 
                     	 ct.innerHTML = "<input type='checkbox' name='szid' value='"+data.szidJsons[szid]+"' />"+data.szidJsons[szid]+""; 	
				    }
				    
				     //添加颜色checkbook
				    document.getElementById("colorTr").innerHTML = "";
				    for( var color in data.colorJsons) {
				    	 
				      //获取颜色列id
                      var coloT=document.getElementById("colorTr");
                      //插入td 
                      var cz = coloT.insertCell(); 
				      if(color==2){
				      	cz.innerHTML = "<input type='checkbox' name='coid' value='"+data.colorJsons[color]+"'/>"+data.colorJsons[color]+"";
				      }else{
	                      cz.innerHTML = "<input type='checkbox' name='coid' value='"+data.colorJsons[color]+"'/>"+data.colorJsons[color]+""; 	
				      }
				    }
				  
				    
				//关闭弹出框
				$("#productList").window('close');
				//修改datagrid的数据
				$('#sku').datagrid('loadData',data_json);
				
				}
			})
		
	}
	
		
	$(function() {
	
		/**
		 *checkbook的选中事件
		 */
		var editRow = undefined; //定义全局变量：当前编辑的行
		str = {};
		var cstr = [];
		var sstr = [];
		str = {cstr:cstr,sstr:sstr};
		var rows = $("#sku").data("org-rows");
		//尺寸chechbox监听
	    $("#sizeTr").click(function() {
	    	//如果datagrid里数据为空，则获取表格里的数据
			if (rows == null)
			{
			     $("#sku").data("org-rows", $("#sku").datagrid("getData"));
			     rows = $("#sku").datagrid("getData");
			}
			
		    //获取checkbox
		    var checkboxes = document.getElementsByName("szid");
		    
		    sstr = [];//清空尺寸check
			for(i=0;i<checkboxes.length;i++){
				if(checkboxes[i].checked){
					sstr.push(checkboxes[i].value);
				}
			}
			str.sstr=sstr;
			$('#sku').datagrid('loadData',loadFilter(rows,str));
	     });
            
	     //颜色chechbox监听
	     $("#colorTr").click(function() {
	     	//如果datagrid里数据为空，则获取表格里的数据
			if (rows == null)
			{
			     $("#sku").data("org-rows", $("#sku").datagrid("getData"));
			     rows = $("#sku").datagrid("getData");
			}
			
		     var checkboxes = document.getElementsByName("coid");
		     
		     cstr = [];
			 for(i=0;i<checkboxes.length;i++){
				if(checkboxes[i].checked){
					cstr.push(checkboxes[i].value);
				}
			}
			 str.cstr=cstr;
	         $('#sku').datagrid('loadData',loadFilter(rows,str));       
	    });
            
        
        /**
	 	 *添加数量
	 	 */
		//双击行事件
		$('#sku').datagrid({
			/**
			onAfterEdit:function(index,row){//在用户完成编辑一行的时候触发
							//endEdit该方法触发此事件
                    		console.info(row);
                    		editRow = undefined;
						},
		
			onDblClickCell: function(index,field,value){
			
						 if (editRow != undefined) {
                        		$('#sku').datagrid("endEdit", editRow);
                        		
                    		}
                   		 if (editRow == undefined) {
                        	$('#sku').datagrid("beginEdit", index);
                        	editRow = index;
                    		}
			
						
						}
					*/
					
					onLoadSuccess:function(data){
						for(var i = 0;i<data.total;i++){
					 		$("#sku").datagrid('beginEdit', i);
						}
					}
			
		});
     
          
	 /**
	  *保存
	  */
	$("#save").click(function() {
		//关闭行内编辑
		var rows = $("#sku").datagrid('getSelections');
	    var rowIndex = $('#sku').datagrid('getRowIndex', rows[0]);
	    $("#sku").datagrid('endEdit', rowIndex);
	   	//获取datagrid的数据
	    var arr=$('#sku').datagrid('getData');
	    var skuJsons = JSON.stringify(arr.rows);
	   
	   	//验证表单
	   	var isValid = $('#procureProductForm').form('validate');
		//判断
		if(isValid){
			$.ajax({
			url : 'procurepsaveProcurep.action',
			type : "POST",
			data : $("#procureProductForm").serialize()+"&skuJsons="+skuJsons,
			dataType : 'json',
			success : function(data){
				if(data){
					//跳转到列表
					removeCurrentPanel('procurepgetAllProcurep','新增采购需求');
				}else{
					$.messager.show({
							msg : '<div style="width:100%"><div style="line-height:40px;text-align:center;">保存失败</div></div>',
							timeout : 800,
							showSpeed : 200,
							showType : 'show',
							style : {
								right : '',
								top :'',
								bottom : ''
							}
						});	
				}	
			}
			});
			return true;
			} else {
			return false;
			}
		
	});  
	  
	   
	   
		
     })
	
	
 
 	/**
	 *过滤
	 */
 	function loadFilter(data,str){  
    	var value = {  
            total:0,  
            rows:[]  
    	};  
    	for (var i = 0; i < data.rows.length; i++) {  
        	var o = _loadArray(data.rows[i],str);  
       		if(o!=undefined){
       			value.rows.push(o);  
       		}
    	}  
    	return value.rows;  
	}  
	
	/**
	 *根据条件筛选
	 */
	function _loadArray(data,pre){  
		if(pre.sstr.length<=0){
			if(pre.cstr.length>=0){
				for(var sst in pre.sstr){
			   		 for (var satt in data) {
			   		 	var attStr = data[satt];
			   		 	if(attStr==pre.sstr[sst]){
			   		 		return data;
			   		 	}
			   		}
			   	}
			}else{
				return data;
			}
		}else{
			if(pre.cstr.length<=0){
				for(var sst in pre.sstr){
					for (var satt in data) {
						var attStr = data[satt];
						if(attStr==pre.sstr[sst]){
							return data;
						}
					}
				}
			}else{
				 for(var cst in pre.cstr){
			   		 for (var att in data) {
			   		 	var row = data[att];
			   		 	if(row==pre.cstr[cst]){
			   		 		
			   		 		for(var sst in pre.sstr){
						   		 for (var satt in data) {
						   		 	var attStr = data[satt];
						   		 	if(attStr==pre.sstr[sst]){
						   		 		return data;
						   		 	}
						   		}
						   	}
			   		 		
			   		 	}
			   		 }
			    }
			}
		}
		
	   
	}  
	
  	/**
	 *上传图片
	 */		
	function uploadImages(){
		$('#win').window('open');
			
	}     
	
	/**
	 *判断文件的格式
	 */
	function checkFile(){
		$("#myFile").html("");
		
		var uploadUrl= $("#uploadUrl").filebox('getValue');
		if(!/\.(rar|zip)$/.test(uploadUrl)){
			
			$("#myFile").append("<font color='red'>*文件类型必须是.rar,zip中的一种</font>");
			
			return false;
		}
		return true;

	
	}
	
	 /**
      *上传文件到服务器
      */     
     function checkUploadUrl(){
      var formData = new FormData(document.getElementById("imageForm" ));
     	//判断照片格式
     	if(checkFile()){
     		$.ajax({
			url : 'procurepuploadFiles',
			type : "POST",
			data: formData,
			processData:false,
            contentType:false,
            dataType : 'json',
			success : function(data) {
				if(data.flag){
					//关闭窗口
					$('#win').window('close'); 
					//清空input的赋值
					$("#blueprint").val("");
					//赋值
					$("#blueprint").val(data.name);
					$("#attachment").append("<font color='red'>"+data.name+"</font>");
				}else{
					$("#myFile").append("<font color='red'>*"+data.name+"</font>");
				}
			
			}
			
		});
     }		
    }
	
	/**
     *下载文件
     */
   	 function downloadFile(){  
   		var blueprint= $("#blueprint").val();
   	 	window.location = 'procurepdownFile.action?fileName='+blueprint;
   	 } 
     
    /**
     *删除文件
     */  
    function deleFile(){  
   		var blueprint= $("#blueprint").val();
   		$.ajax({
				type : 'POST',
				async: false,
				url : 'procurepdeleteFile',
				data : {
					'fileName' : blueprint
				},
				dataType : 'json',
				success : function(data) {
   					if(data){
   					//清空input的赋值
					$("#blueprint").val("");
					$("#attachment").html("");
   					}else{
   						$.messager.show({
							msg : '<div style="width:100%"><div style="line-height:50px;text-align:center;">文件删除失败！</div></div>',
							timeout : 800,
							showSpeed : 200,
							showType : 'show',
							style : {
								right : '',
								top :'',
								bottom : ''
							}
						});
   					}
   				}
   			})
   	 }  
   	     	
   /**
    *返回
    */
    function goBackFavor(url,title){
    
    	var tabbar = window.parent.$('#tabs');
		var tab = tabbar.tabs('getSelected');

		if (tab){
			var index = tabbar.tabs('getTabIndex', tab);
		
			if(url != null){
				addPanelExists(url,title);
				tabbar.tabs('close', index);
			}else{
				tabbar.tabs('close', index);
			}
		}
    }
</script>

<style type="text/css">
	.form-table {
		width:100%;
		padding: 20px 0px 20px 40px;
	}
	
	.form-table tr td {
		padding:5px;
	}
	
	.form-table tr td:first-child {
		width: 7.5em;
	}
	
</style>
<body>
	<div style="display: none;">
		<!-- 产品信息  -->
		<div id="productList" class="easyui-window"  title="产品信息" collapsible="false"  minimizable="false"  maximizable="false" closed="true"  modal="true"
			 style="width:800px;height:540px; padding: 10px;" href="productgetAllProduct.action"> 
		</div>  
		<div id="win" class="easyui-window" title="文件上传"  style="width:350px;height:200px;" collapsible="false" minimizable="false" maximizable="false" closed="true" >
			<div align="center" style="margin-top: 20px;" class="toolbar">
			<form id="imageForm" action="" method="post" enctype="multipart/form-data">  
				<table style="margin-top: 15px;">    
			    	<tr>  
			        	<td>上传附件&nbsp;</td>  
			            <td><input class="easyui-filebox" id="uploadUrl" name="myFile" buttonText="浏览" style="width:120px;" data-options="onChange:function(){checkFile()}" /></td>  
			        </tr> 
			        <tr style="text-align: center;">
			        	<td colspan="2" style="height:30px;"><span id="myFile"></span></td>
			        </tr>
			        <tr style="text-align: center;">  
			            <td colspan="2" >
			            	<input class="easyui-linkbutton" type="button"  value="上传" onclick="checkUploadUrl();"/>
			            	<span style="margin-right: 10px;"></span>
			            	<input class="easyui-linkbutton" type="reset" value="重置">
			            </td>  
			         </tr>  
			     </table>  
			  </form>  
			</div>
		</div>
	</div>
	<div id="content" style="width: 100%;">
		<form id="procureProductForm" action=""  method="post" arget="_blank">
			<div id="contentOne" style="width: 70%;float: left;">
				<table class="form-table">
					<tr>
						<td>产品款号</td>
						<td>
							<input class="easyui-textbox" id="productCode" name="procureProduct.productCode" value="" style="width: 120px; height: 26px;" readonly="true" required="true" missingMessage="不能为空"/> 
							<input class="easyui-linkbutton" type="button" id="query" style="border-color: #95B8E7; color: #95B8E7" onclick="showProductList()" value="…">
						</td>
						
						<td>供应商数量</td>
						<td>
							<input class="easyui-numberbox" id="" name="procureProduct.suppelierCount" value="" style="height: 26px;"  required="true" missingMessage="不能为空"/>
						</td>
					</tr>
					
					<tr>
						<td>采购数量</td>
						<td>
							<input class="easyui-numberbox" id="" name="procureProduct.procCount" value="" style="height: 26px;"  required="true" missingMessage="不能为空"/>
						</td>
						
						<td>交货时间</td>
						<td >
							<input class="easyui-datebox" id="" name="procureProduct.deliveryDate" value="" style="height:26px;"  required="true" missingMessage="不能为空" />
						</td>
					</tr>
					
					<tr>
						<td>开始时间</td>
						<td>
							<input class="easyui-datebox" id="" name="procureProduct.startTime" value="" style="height: 26px;"  required="true" missingMessage="不能为空"/>
						</td>
						
						<td>结束时间</td>
						<td >
							<input class="easyui-datebox" id="" name="procureProduct.endTime" value="" style="height:26px;"  required="true" missingMessage="不能为空"/>
							<input name="procureProduct.blueprint"  id="blueprint" style="display:none;" value="" /> 
						</td>
					</tr>
					
					<tr>
						<td></td>
						<td>
							<img  alt=""  src="images/attachment.png" style="height: 26px;"></img><a onclick="uploadImages()" style="cursor:pointer">上传附件</a>
						</td>
					</tr>
					<tr>
						<td></td>
						<td>
							<img alt="" src="images/attachment.png" style="height: 26px;" ></img><a onclick="downloadFile()" style="cursor:pointer"><span id="attachment"></span></a><a onclick="deleFile()" style="cursor:pointer;padding-left:15px;">删除</a>
						</td>
					</tr> 
				</table>
			</div>	
			
			<div style="margin-left:40px;padding-top: 240px">
				<span style="display:block;display:inline-block;"><h2>按sku采购</h2></span>
				<div style="margin-bottom:10px;border:1px solid #95B8E7;width:60%;">
				 	<table>
				 		<tr id="sizeTr"></tr>
				 		<tr id="colorTr"></tr>
				 	</table>
				</div>
				<table id="sku" class="easyui-datagrid" style="width:45%;height:340px; " singleSelect="true" id="partCrafs">
					<thead>
						<tr>
							<th data-options="field:'code'" width="" align="center">序号</th>
							<th data-options="field:'skuCode'" width="150px" align="center">产品SKU</th>
							<th data-options="field:'cona'" width="100px" align="center" width="110px;">颜色</th>
							<th data-options="field:'szid'" width="100px" align="center">尺寸</th>
							<th data-options="field:'purchaseNum'" width="100px" align="center" sortable="true" editor="{type:'numberbox'}">采购数量</th>
							<th data-options="field:'productCode'" hidden="true" align="center" >产品编码</th>
							<th data-options="field:'coloId'" hidden="true" align="center" >颜色id</th>
							<th data-options="field:'colo'" hidden="true" align="center" >颜色编码</th>
							<th data-options="field:'szco'" hidden="true" align="center" >尺寸编码</th>
						</tr>
					</thead>
				</table>
			</div>
			<div style="margin-top: 30px;margin-left: 360px; ">
				<input id="save" class="easyui-linkbutton" type="button" value="保存" style="padding: 5px 12px 5px 12px;"/>
				<a class="easyui-linkbutton" onclick="removeCurrentPanel();" style="margin-left: 10px;">返回</a>
			</div>
		</form>
	</div>
</body>
</html>